<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Infotech Ltd.
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2005/10/24 22:15:35 $)
// $RCSfile: functions_departments.php,v $ : $Revision: 1.16 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}


/**
* ###############################################
* CLASS DECLARATIONS
* ###############################################
*/

/**
* Class that handles all department related stuff
*/
class Departments
{
	/**
	* Gets the department title from the given id
	*/
	function getDepartmentNameFromId($depid)
	{
		global $_SWIFT, $dbCore;

		$Record = $dbCore->queryFetch("SELECT `title` FROM `". TABLE_PREFIX ."departments` WHERE `departmentid` = '". intval($depid) ."';");

		return $Record["title"];
	}

	/**
	* Get total number of departments in system
	*/
	function getDepartmentCount()
	{
		global $_SWIFT, $dbCore, $datastore;
		
		$datastore->load("departmentcache");


		return count($_SWIFT["departmentcache"]);
	}

	/**
	* Gets the display order number for the next insert
	*/
	function getLastDepartmentDisplayOrder()
	{
		global $_SWIFT, $dbCore, $datastore;

		$datastore->load("departmentcache");

		// Get Last Insert ID
		$linsertid = max(array_keys($_SWIFT["departmentcache"]));
		
		$disporder = $_SWIFT["departmentcache"][$linsertid]["displayorder"]+1;
		return $disporder;
	}

	/**
	* Inserts a new department
	*/
	function insertDepartment($title, $departmentmodule, $tgroupidlist, $type = "1", $displayorder = "1", $isdefault = false)
	{
		global $_SWIFT, $dbCore;

/*
		if ($isdefault && _is_array($tgroupidlist))
		{
			$depidlist = array();
			$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."tgroupassigns` WHERE `tgroupid` IN(". buildIN($tgroupidlist) .") AND `type` = '". TGROUP_DEPARTMENT ."';");
			while ($dbCore->nextRecord())
			{
				$depidlist[] = $dbCore->Record["toassignid"];
			}

			// Now unset the default status for all other departments under this group

			$dbCore->query("UPDATE `". TABLE_PREFIX ."departments` SET `isdefault` = '0' WHERE `departmentid` IN (". buildIN($depidlist) .");");

			$nisdefault = "1";
		} else {
			$nisdefault = "0";
		}*/
		$nisdefault = 0;

		$departmentmodule = cleanVar($departmentmodule);

		// Insert the department
		$dbCore->query("INSERT INTO `". TABLE_PREFIX ."departments` (`title`, `departmenttype`, `departmentmodule`, `isdefault`, `displayorder`) VALUES ('". $dbCore->escape($title) ."', '". iif($type=="1", "public", "private") ."', '". $dbCore->escape($departmentmodule) ."', '". $dbCore->escape($nisdefault) ."', '". $dbCore->escape($displayorder) ."');");
		$departmentid = $dbCore->lastInsertId();
		if (!$departmentid)
		{
			return false;
		}

		insertTemplateGroupAssignLink($tgroupidlist, TGROUP_DEPARTMENT, $departmentid, false);

		// Rebuild the department cache
		rebuildDepartmentCache();
		
		return $departmentid;
	}

	/**
	* Deletes a department from the array of department ids passed to it
	*/
	function deleteDepartments($departmentidarray)
	{
		global $dbCore, $_SWIFT;

		if (!is_array($departmentidarray))
		{
			return false;
		}

		// Delete the departments
		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."departments` WHERE `departmentid` IN (". buildIN($departmentidarray) .");");
		// Delete all assignments for the current departments
		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."staffassigns` WHERE `departmentid` IN (". buildIN($departmentidarray) .");");
		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."groupassigns` WHERE `departmentid` IN (". buildIN($departmentidarray) .");");

		deleteTemplateGroupAssignLinks($departmentidarray, TGROUP_DEPARTMENT);

		rebuildDepartmentCache();
	}
}






/**
* ###############################################
* FUNCTION DECLARATIONS
* ###############################################
*/

/**
* Rebuilds the entire department cache
*/
function rebuildDepartmentCache()
{
	global $_SWIFT, $dbCore, $datastore;

	$deparray = array();

	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."departments` ORDER BY `displayorder` ASC;");
	$departmentindex = 0;
	while ($dbCore->nextRecord())
	{
		$deparray[$dbCore->Record["departmentid"]] = $dbCore->Record;
		if ($dbCore->Record["departmentmodule"] == MODULE_TICKETS)
		{
			$departmentindex++;
			$deparray[$dbCore->Record["departmentid"]]["index"] = $departmentindex;
		}
	}

	$datastore->update("departmentcache", $deparray);
}

/**
* Render the department form for edit/insert
*/
function renderDepartmentForm($type)
{
	global $dbCore, $_SWIFT, $departments, $module;

	printFormStart();
	printMainTableHeader($_SWIFT["language"]["departmentdetails"]);

	printTextRow("title", $_SWIFT["language"]["deptitle"], $_SWIFT["language"]["desc_deptitle"], "text", $_POST["title"]);
	
	if ($type == INSERT)
	{
		$displayorder = count($_SWIFT["departmentcache"]);
	} else {
		$displayorder = $_POST["displayorder"];
	}
	printNumberRow("displayorder", $_SWIFT["language"]["displayorder"], $_SWIFT["language"]["desc_displayorder"], $displayorder);

	if ($_POST["departmenttype"] == "public" || empty($_POST["departmenttype"]))
	{
		$deptype = true;
	} else {
		$deptype = false;
	}

	printPublicPrivateRow("type", $_SWIFT["language"]["deptype"], $_SWIFT["language"]["desc_deptype"], $deptype);
//	printYesNoRow("isdefault", $_SWIFT["language"]["defaultdep"], $_SWIFT["language"]["desc_defaultdep"], iif(empty($_POST["isdefault"]), false, $_POST["isdefault"]));

	addHiddenField("isdefault", "1");

	$index = 0;
	// Display only if tickets module is registered
	if ($module->isRegistered(MODULE_TICKETS))
	{
		$options[$index]["title"] = $_SWIFT["language"]["module_tickets"];
		$options[$index]["value"] = MODULE_TICKETS;
		$index++;
	}
	// Display only if bug tracking module is registered
	if ($module->isRegistered(MODULE_BUGS))
	{
		$options[$index]["title"] = $_SWIFT["language"]["module_bugs"];
		$options[$index]["value"] = MODULE_BUGS;
		$index++;
	}
	// Display only if live support module is registered
	if ($module->isRegistered(MODULE_LIVESUPPORT))
	{
		$options[$index]["title"] = $_SWIFT["language"]["module_livesupport"];
		$options[$index]["value"] = MODULE_LIVESUPPORT;
		$index++;
	}
	// Display only if SWIFTPRODUCT is HelpBase
	if (SWIFTPRODUCT == PRODUCT_HELPBASE)
	{
		$options[$index]["title"] = $_SWIFT["language"]["module_knowledgebase"];
		$options[$index]["value"] = MODULE_KNOWLEDGEBASE;
		$index++;
	}

	printSelectRow("departmentmodule", $_SWIFT["language"]["departmentmodule"], $_SWIFT["language"]["desc_departmentmodule"], $options);

	printTGroupRow("tgroupid", $_SWIFT["language"]["templategroups"], $_SWIFT["language"]["desc_templategroups"], $type, TGROUP_DEPARTMENT, $_POST["departmentid"]);

	printSubmitRow(iif($type==INSERT, $_SWIFT["language"]["insertdepartment"], $_SWIFT["language"]["update"]));

	printMainTableFooter();

	addHiddenField("_m", "core");
	addHiddenField("_a", iif($type==INSERT, "insertdepartment", "editdepartment"));
	addHiddenField("step", "1");
	if ($type == EDIT)
	{
		addHiddenField("departmentid", $_POST["departmentid"]);
	}
	printFormEnd();
}

/**
* Update a department
*/
function updateDepartment($departmentid, $title, $departmentmodule, $tgroupidlist, $type = "1", $displayorder = "1", $isdefault = false)
{
	global $_SWIFT, $dbCore;
/*
	if ($isdefault && _is_array($tgroupidlist))
	{
		// Reset department for all Template Groups
		$dbCore->query("UPDATE `". TABLE_PREFIX ."templategroups` SET `departmentid` = '0' WHERE `tgroupid` IN (". buildIN($tgroupidlist) .");");

		// Set this department as default
		$dbCore->query("UPDATE `". TABLE_PREFIX ."templategroups` SET `departmentid` = '". intval($departmentid) ."' WHERE `tgroupid` IN (". buildIN($tgroupidlist) .");");
	}*/

	$departmentmodule = cleanVar($departmentmodule);

	// Update the department
	$dbCore->query("UPDATE `". TABLE_PREFIX ."departments` SET `title` = '". $dbCore->escape($title) ."', `departmenttype` = '". iif($type=="1", "public", "private") ."', `departmentmodule` = '". $dbCore->escape($departmentmodule) ."', `displayorder` = '". $dbCore->escape($displayorder) ."' WHERE `departmentid` = '". intval($departmentid) ."';");

	insertTemplateGroupAssignLink($tgroupidlist, TGROUP_DEPARTMENT, $departmentid, true);

	// Rebuild the department cache
	rebuildDepartmentCache();

	return $departmentid;
}
?>